﻿CROSS_COMPILE 	?= arm-none-eabi-
TARGET		  	?= demo

DEFS       = -DAT32F421C8T7  -DUSE_STDPERIPH_DRIVER -DAT_START_F421_V1_0 -DSPECIAL_64
CFLAGS    += $(DEFS)

CC 				:= $(CROSS_COMPILE)gcc
LD				:= $(CROSS_COMPILE)ld
OBJCOPY 	:= $(CROSS_COMPILE)objcopy
OBJDUMP 	:= $(CROSS_COMPILE)objdump
SIZE      := $(CROSS_COMPILE)size

#SUBDIRS :=$(shell ls -l |grep ^d | awk '{print $9}')
#SUBDIRS :=third_party
export INCDIRS SRCDIRS

#subsystem:
#	cd $(SUBDIRS) && make

#windows 10 libpath
LIBPATH			:= -lgcc -L D:/2019-q4-major/lib/gcc/arm-none-eabi/9.2.1 -lgcc -L D:\2019-q4-major\arm-none-eabi\lib
#linux  libpath
#LIBPATH			:= -lgcc -L /usr/lib/gcc/arm-none-eabi/4.9.3

INCDIRS 		+= include/CMSIS		\
								include/common \
								include/driver \
								include/bsp/at32f421 \
								driver/lib/inc
								
#third_party/letter-shell
			   
SRCDIRS			+= arch/ARM_M4 \
								driver/lib/src \
								driver/at32F4xx \
								bsp/at32f421/project \
								include/common \
								bsp/at32f421
#third_party/letter-shell  添加失败  shell.c vsnprintf无法编译通过
								
#给每个参数添加 -I			   
INCLUDE			:= $(patsubst %, -I %, $(INCDIRS))

#获得每个文件的路径
# $(wildcard pattern)  wildcard 会以 pattern 这个格式，去寻找存在的文件，返回存在文件的名字
SFILES			:= $(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.S))
CFILES			:= $(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.c))

#notdir 将路径去掉 只剩文件名
#SFILENDIR = start.S
#CFILENDIR = main.c bsp_beep.c bsp_delay.c bsp_led.c bsp_key.c bsp_gpio.c bsp_clk.c
SFILENDIR		:= $(notdir  $(SFILES))
CFILENDIR		:= $(notdir  $(CFILES))

#$(patsubst pattern,replacement,\$(var))
#patsubst 函数是从 var 变量里面取出每一个值，如果这个符合 pattern 格式，把它替换成 replacement 格式
SOBJS			:= $(patsubst %, obj/%, $(SFILENDIR:.S=.o))
COBJS			:= $(patsubst %, obj/%, $(CFILENDIR:.c=.o))
#所有的 *.o文件
OBJS			:= $(SOBJS) $(COBJS)
VPATH			:= $(SRCDIRS)

.PHONY: clean show_value
	
$(TARGET).bin : $(OBJS)
	$(LD) -Tmap.lds -o $(TARGET).elf $^ $(LIBPATH)
	$(OBJCOPY) -O binary -S $(TARGET).elf $@ 
	$(OBJCOPY) -O ihex $(TARGET).elf $(TARGET).hex
	$(OBJDUMP) -D -m arm $(TARGET).elf > $(TARGET).dis
	$(SIZE) $(TARGET).elf

#编译所有汇编文件
$(SOBJS) : obj/%.o : %.S
	$(CC) -Wall -nostdlib -fno-builtin -c -O2  $(INCLUDE) -o $@ $<

#编译所有c文件 -march=armv7-m
$(COBJS) : obj/%.o : %.c
	$(CC) $(CFLAGS) -mcpu=cortex-m4 -Wa,-mimplicit-it=thumb -nostdlib -mthumb -fno-builtin -c -O2  $(INCLUDE) -o $@ $<


clean:
	rm -rf $(TARGET).elf $(TARGET).dis $(TARGET).bin $(COBJS) $(SOBJS) $(TARGET).hex

show_value:
	@echo INCLUDE=$(INCLUDE)
	@echo SOBJS = ${SOBJS}
	@echo COBJS = ${COBJS}
	@echo CFILES = ${CFILES}
	@echo SFILES = ${SFILES}
	@echo SFILENDIR = $(SFILENDIR)
	@echo CFILENDIR = $(CFILENDIR)
	@echo LIBPATH = $(LIBPATH)
	@echo SUBDIRS = $(SUBDIRS)
